package cn.dubito.miaosha.controller.access.interceptor;

import cn.dubito.miaosha.config.UserContext;
import cn.dubito.miaosha.controller.access.AccessLimit;
import cn.dubito.miaosha.controller.vo.CodeMsg;
import cn.dubito.miaosha.controller.vo.Result;
import cn.dubito.miaosha.domain.SeckillUser;
import cn.dubito.miaosha.redis.AccessKey;
import cn.dubito.miaosha.redis.RedisService;
import cn.dubito.miaosha.service.SeckillUserService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liliang
 * @description:  拦截器 (需要注册
 * @date 2018/4/13.
 */
@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private SeckillUserService userService;

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            SeckillUser user = getUser(request, response);
            UserContext.setUser(user);

            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit annLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (annLimit == null) {
                return true;
            }

            int seconds = annLimit.seconds();
            int maxCount = annLimit.hitCount();
            boolean needLogin = annLimit.needLogin();
            String key = request.getRequestURI();
            if (needLogin) {
                if (user == null) {
                    render(response, CodeMsg.SESSION_ERROR);
                    return false;
                }
                key += user.getId();
            }

            AccessKey ak = AccessKey.withExpire(seconds);
            // 访问次数
            Integer count = redisService.get(ak, key, Integer.class);
            if (count == null) {
                redisService.set(ak, key, 1);
            } else if (count < maxCount) {
                redisService.incr(ak, key);
            } else {
                render(response,CodeMsg.HIT_LIMIT);
                return false;
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, CodeMsg msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream stream = response.getOutputStream();
        String str = JSON.toJSONString(Result.error(msg));
        stream.write(str.getBytes("UTF-8"));
        stream.flush();
        stream.close();
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @param response
     * @return
     */
    private SeckillUser getUser(HttpServletRequest request, HttpServletResponse response) {
        String paramToken = request.getParameter(SeckillUserService.COOKIE_NAME_TOKEN);
        String cookieToken = getCookieValue(request, SeckillUserService.COOKIE_NAME_TOKEN);
        boolean cookieIsNull = StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken);
        if (cookieIsNull) {
            return null;
        }
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        return userService.getByToken(response, token);
    }

    /**
     * 获取 Cookie 里面的值
     *
     * @param request
     * @param cookieName
     * @return
     */
    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
